//
//  JWFindFreightShopRuZhuVC.m
//  jinwang
//
//  Created by jzb on 2018/4/13.
//  Copyright © 2018年 jzb. All rights reserved.
//

#import "JWFindFreightShopRuZhuVC.h"

@interface JWFindFreightShopRuZhuVC ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    
    NSMutableArray       *_imageArray;
    NSArray *arr;
    NSMutableArray *_selectedPhotos;
}
@property (nonatomic,strong)UIImagePickerController *pickerController;

@property (weak, nonatomic) IBOutlet UIButton *firstBtn;
@property (weak, nonatomic) IBOutlet UIButton *secondBtn;

@property (nonatomic,strong) UIImage *iamge01;
@property (nonatomic,strong) UIImage *iamge02;
@property (nonatomic,assign) int btnNum;

@end

@implementation JWFindFreightShopRuZhuVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"商家入驻";
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.f) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    _btnNum = 0;
    _imageArray = [NSMutableArray array];
    if (_pickerController == nil) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            _pickerController = [[UIImagePickerController alloc] init];
            _pickerController.view.backgroundColor = [UIColor redColor];
            _pickerController.delegate = self;
            _pickerController.allowsEditing = YES;
        });
    }
}
- (IBAction)FreightShopRuZhuBtnOnclick:(UIButton *)sender {
    
    if (sender.tag == 1000) {
        _btnNum = 1;
        [self pickerControllerChose];
        
    }else if (sender.tag == 1001){
         _btnNum = 2;
        [self pickerControllerChose];
        
    }else{
        if (_imageArray.count == 0) {
            [self showBottomMessag:@"请选择照片"];
        }else{
            NSLog(@"-=-=-=-=>>%@",_imageArray);
            [self uploadImages];
        }
        
    }
    
}
- (void)pickerControllerChose{
    
    UIAlertController*ZhengC=[UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction*XiangCe=[UIAlertAction actionWithTitle:@"从手机相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:_pickerController animated:YES completion:nil];
    }];
    UIAlertAction*ZhaoXiang=[UIAlertAction actionWithTitle:@"打开照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:_pickerController animated:YES completion:nil];
        
    }];
    UIAlertAction*  Cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    
    [ZhengC addAction:XiangCe];
    [ZhengC addAction:ZhaoXiang];
    [ZhengC addAction:Cancel];
    [self presentViewController:ZhengC animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
   
    
    UIImage *userImage = info[UIImagePickerControllerEditedImage];
    [_pickerController dismissViewControllerAnimated:YES completion:nil];
    if (_btnNum == 1) {
        if (_iamge01) {
            [_imageArray removeObject:_iamge01];
        }
        _iamge01 = [self imageCompressForWidth:userImage targetWidth:_firstBtn.width];
        [_firstBtn setImage:_iamge01 forState:UIControlStateNormal];
        [_imageArray addObject:_iamge01];
    }else if (_btnNum == 2){
        if (_iamge02) {
            [_imageArray removeObject:_iamge02];
        }
        _iamge02 = [self imageCompressForWidth:userImage targetWidth:_secondBtn.width];
       [_secondBtn setImage:_iamge02 forState:UIControlStateNormal];
        [_imageArray addObject:_iamge02];
    }
}

#pragma mark ------------图片处理------------------
-(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    //    UIGraphicsBeginImageContext(size);
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    
    UIGraphicsEndImageContext();
    return newImage;
}
//照片上传到七牛
- (void)uploadImages{
    if (_imageArray.count > 0) {
        _selectedPhotos = [NSMutableArray new];
        for (int i=0; i<_imageArray.count; i++){
            if ([_imageArray[i] isKindOfClass:[UIImage class]]) {
                [_selectedPhotos addObject:_imageArray[i]];
                [_imageArray removeObjectAtIndex:i];
                i--;
            }
        }
        //将图片上传到服务器
        [NSThread sleepForTimeInterval:0.5];
        if (_selectedPhotos.count > 0) {
            
            [UploadImageTool uploadImages:_selectedPhotos progress:^(CGFloat totalProgress) {
                
            } success:^(NSArray *urlArr) {
                
                NSLog(@"-=-=-=-=>>%@",urlArr);
                if (urlArr.count == 1) {
                    [self makeUrl_Freight_enterImg1:urlArr[0] img2:@""];
                }else if (urlArr.count == 2){
                    [self makeUrl_Freight_enterImg1:urlArr[0] img2:urlArr[1]];
                }
            } failure:^{
                
            }];
        }
        
    }else {
        [self showBottomMessag:@"请选择照片"];
    }
}
//商家入驻
-(void)makeUrl_Freight_enterImg1:(NSString *)img1
                            img2:(NSString *)img2{
    [[DDNetworkManagerDate makeUrl_Freight_enterWithtoken:k_user_token img1:img1 img2:img2] post_RequestFinshSuccess:^(id responseObject) {
        if ([self requestFinshCode:responseObject isShowMessage:YES] == 1) {
            [self goBack];
        }
    } failure:^(id errorObject) {
        
        [self showBottomMessag:@"网络请求失败"];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
